package com.shop.model.impl;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.shop.driver.MySql;


public abstract class BaseModel 
{
	private static long timer;
	
	//驱动对象
	private static MySql mySql ;
	
	//表名
	protected String tableName;
	
	//表前缀
	protected String tableNamePerfix;
	
	public String getTableName() {
		return tableName;
	}


	public void setTableName(String tableName) {
		this.tableName = tableName;
	}


	public String getTableNamePerfix() {
		return tableNamePerfix;
	}


	public void setTableNamePerfix(String tableNamePerfix) {
		this.tableNamePerfix = tableNamePerfix;
	}


	//当前模型
	private static BaseModel curretModel;
	
	private static Map<String, BaseModel> baseModel = new HashMap<String, BaseModel>();
	
	public static BaseModel getIntance(Class<?> className) throws Exception
	{
		if(timer == 0 ) {
			timer = System.currentTimeMillis() ;
		}
		
		if(timer+60000 - System.currentTimeMillis() < 0) {
			timer = 0;
			baseModel.clear();
		}
//		System.out.println(baseModel.equals(null)); System.exit(0);
		
		
		if (baseModel.get(className.getName()) instanceof BaseModel) {
			
			return baseModel.get(className.getName());
					
		} else {
			
		
			Object[] args = null;
			
			curretModel =(BaseModel)className.getMethod("getInstances", null).invoke(null, args);
			
			baseModel.put(className.getName(), curretModel);
			
			return curretModel;
		}
	}
	
	
	public MySql getConnect()
	{
		return mySql==null ? mySql = MySql.getInitance(new Properties(), "/config/jdbc.properties") : mySql;
	}
	
	/**
	 * 获取数据库字段
	 * @param tableName 表名
	 * @param DbName    数据库名
	 */
	protected void setModelDbFields(Object obj, String tableName, String DbName) 
	{
		this.getConnect();
		List<?> fields =  mySql.getField(tableName, DbName);
		
		String[] dbFields = new String[fields.size()];
		
		int j = 0;
		for(Object f : fields)
		{
			dbFields[j] = (String) f;
			j++;
		}
		
		
		Field[] field = obj.getClass().getDeclaredFields();
		Field.setAccessible(field, true);
		
		for( int i = 0; i<= field.length-1; i++)
		{
			if(field[i].getName().indexOf("public") == -1 && field[i].getName().indexOf("_d") != -1)
			{
				try {
					field[i].set(obj, dbFields[i]);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	protected BaseModel() {
		
	}


	public static Object getCurretModel() {
		return curretModel;
	}


	public static void setCurretModel(BaseModel curretModel) {
		BaseModel.curretModel = curretModel;
	}

}
